package com.phonegapandroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;

import com.google.android.c2dm.C2DMessaging;
import com.phonegap.DroidGap;

//import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends DroidGap implements LocationListener{
	
	private LocationManager locationManager;	
	private String provider;
	
	private SharedPreferences appSettings;
	private Boolean isRegistered;
	private Runnable registerRunable;

	/* Web Service Variables */
	private String URL;
	private String METHOD_NAME;
	private String NAMESPACE;
	private String SOAP_ACTION;

	private String strRegistrationID;
	private String strDeviceID;
	private String strClientWebId;
	private String strGoogleId;

	// private Location myLocation ;
	private double myLatitude;
	private double myLongitude;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setIntegerProperty("splashscreen", R.drawable.splash);
		setVariables();
		super.loadUrl("file:///android_asset/www/index.html", 1000);

		registerRunable = new Runnable() {
			@Override
			public void run() {
				registerDevice();
				sendLocation();
			}
		};

		if (isNetworkAvailable()) {
			Thread threadRegister = new Thread(null, registerRunable,
					"MagentoBackground");
			threadRegister.start();
		} else {
			Log.e("Connection not available", "No active connection available");
		}
		
		
		
		
	}

	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null;
	}

	private void registerDevice() {
		if (!isRegistered) {
			if (registerDeviceWithC2DM()) {
				if (registerDeviceWithApplicationServer(strClientWebId,
						strRegistrationID, strDeviceID)) {
					SharedPreferences.Editor prefEditor = appSettings.edit();
					prefEditor.putBoolean("isRegistered", true);
					prefEditor.commit();
					Log.e("Registration Success",
							"Device registered successfully with both servers");
					// runOnUiThread(returnRes);
				}
			}
		} else {
			Log.e("Already Registered",
					"No need of registration, device already registered");
		}

		// Log.e("device register service","Device registration has been finished");
	}
	

	private Boolean registerDeviceWithC2DM() {
		Boolean flag = false;
		strRegistrationID = "thisisregid";
		flag = true;
		/**
		 * try { C2DMessaging.register(this, strGoogleId); try { while
		 * (strRegistrationID == null || strRegistrationID.equals("")) {
		 * Thread.sleep(2000); strRegistrationID =
		 * C2DMessaging.getRegistrationId(this); } } catch (InterruptedException
		 * e) { // TODO Auto-generated catch block
		 * Log.e("0001:Error registering c2dm", e.getMessage());
		 * e.printStackTrace(); } flag = true; } catch (Exception e) {
		 * Log.e("0001:Error registering c2dm", e.getMessage()); flag = false; }
		 **/

		return flag;
	}

	private Boolean registerDeviceWithApplicationServer(String clientWebId,
			String registrationId, String DeviceId) {
		Boolean flag = false;
		try {

			if (strRegistrationID != null && !strRegistrationID.equals("")) {
				ParseWebService();
				flag = true;
			}
		} catch (Exception e) {
			Log.e("0002:Error in register device with app server",
					e.getMessage());
			flag = false;
		}
		return flag;
	}

	private Boolean sendLocation() {
		Boolean flag = false;
		try {
			METHOD_NAME = "InsertAnalytics";
			NAMESPACE = "http://www.mobile-app.centricsource.com/webservice/";
			SOAP_ACTION = NAMESPACE + METHOD_NAME;

			/**
			 * Log.e("METHOD_NAME", METHOD_NAME); Log.e("NAMESPACE", NAMESPACE);
			 * Log.e("SOAP_ACTION", SOAP_ACTION); Log.e("URL", URL);
			 * Log.e("DeviceID", strDeviceID);
			 **/

			ParseWebServiceForLocation();
			flag = true;
			String msg=" Lat = " + String.valueOf(myLatitude)  + "And Long = " + String.valueOf(myLatitude);
			Log.e("Success Send Location",  msg);

		} catch (Exception e) {
			Log.e("0002:Error in sending location with app server",
					e.getMessage());
			flag = false;
		}
		return flag;
	}

	private String getStreamTextByLine(String fileName, int lineNumber) {
		String strOut = "";
		String line = "";
		int counter = 1;
		AssetManager assetManager = getAssets();
		try {
			InputStream in = assetManager.open(fileName);
			if (in != null) {
				InputStreamReader input = new InputStreamReader(in);
				BufferedReader buffreader = new BufferedReader(input);
				while ((line = buffreader.readLine()) != null) {
					if (counter == lineNumber) {
						strOut = line;
					}
					counter++;
				}
				in.close();
			} else {
				Log.e("Input Stream Problem",
						"Input stream of text file is null");
			}
		} catch (Exception e) {
			Log.e("0003:Error in get stream", e.getMessage());
		}
		return strOut;
	}

	
	//hello
	private void setVariables() {
		appSettings = getSharedPreferences("PGAndroidPreferences", MODE_PRIVATE);
		isRegistered = appSettings.getBoolean("isRegistered", false);

		strGoogleId = getStreamTextByLine("andriodinfo.txt", 3);
		strDeviceID = Secure.getString(getBaseContext().getContentResolver(),
				Secure.ANDROID_ID);
		strClientWebId = getStreamTextByLine("andriodinfo.txt", 1);
		URL = getStreamTextByLine("andriodinfo.txt", 2);
		METHOD_NAME = "RegisterAndriod";
		NAMESPACE = "http://www.mobile-app.centricsource.com/webservice/";
		SOAP_ACTION = NAMESPACE + METHOD_NAME;

		// Get the location manager
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// Define the criteria how to select the locatioin provider -> use
		// default
		Criteria criteria = new Criteria();
		provider = locationManager.getBestProvider(criteria, false);
		Location location = locationManager.getLastKnownLocation(provider);

		// Initialize the location fields
		if (location != null) {
			System.out.println("Provider " + provider + " has been selected.");
			
			myLatitude = location.getLatitude();
			myLongitude = location.getLongitude();
			/*
			int lat = (int) (location.getLatitude());
			int lng = (int) (location.getLongitude());
			latituteField.setText(String.valueOf(lat));
			longitudeField.setText(String.valueOf(lng));
			*/
			
			
		} else {
			
			System.out.println("Provider not available");
			/*
			latituteField.setText("Provider not available");
			longitudeField.setText("Provider not available");
			*/
			
		}
		
		
		//myLatitude = 24.963484241951342;
		//myLongitude = 69.3951416015625;

	}

	private Boolean ParseWebService() throws IOException,
			XmlPullParserException, JSONException {

		// String strMethodName = "RegisterAndriod";
		// METHOD_NAME = "RegisterAndriod";
		SOAP_ACTION = "http://www.mobile-app.centricsource.com/webservice/RegisterAndriod";
		Boolean flagResult = false;
		SoapObject request = new SoapObject(NAMESPACE, "RegisterAndriod");

		request.addProperty("ClientWebId", strClientWebId);
		request.addProperty("DeviceId", strDeviceID);
		request.addProperty("Registerid", strRegistrationID);
		request.addProperty("SandBox", 1);

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;

		envelope.implicitTypes = true;
		envelope.encodingStyle = "utf-8";
		envelope.enc = SoapSerializationEnvelope.ENC2001;
		envelope.xsd = SoapEnvelope.XSD;
		envelope.xsi = SoapEnvelope.XSI;

		envelope.setOutputSoapObject(request);
		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);

		androidHttpTransport.call(SOAP_ACTION, envelope);
		androidHttpTransport
				.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

		androidHttpTransport.debug = true;
		String strTemp = envelope.getResponse().toString();
		Log.e("strTemp", strTemp);

		try {
			if (strTemp.equalsIgnoreCase("true")) {
				flagResult = true;
			}

		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return flagResult;
	}

	private Boolean ParseWebServiceForLocation() throws IOException,
			XmlPullParserException, JSONException {

		METHOD_NAME = "InsertAnalytics";

		Boolean flagResult = false;
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

		request.addProperty("Latitude", String.valueOf(myLatitude));
		request.addProperty("Longitude", String.valueOf(myLongitude));
		request.addProperty("ClientWebId", strClientWebId);
		request.addProperty("DeviceId", strDeviceID);
		request.addProperty("DeviceType", 2);
		try {
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelope.dotNet = true;

			envelope.implicitTypes = true;
			envelope.encodingStyle = "utf-8";
			envelope.enc = SoapSerializationEnvelope.ENC2001;
			envelope.xsd = SoapEnvelope.XSD;
			envelope.xsi = SoapEnvelope.XSI;

			envelope.setOutputSoapObject(request);
			AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
					URL);

			androidHttpTransport.call(SOAP_ACTION, envelope);
			androidHttpTransport
					.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

			androidHttpTransport.debug = true;
			// String strTemp = envelope.getResponse().toString();
			// Log.e("Location Service Response", strTemp);

			// if (strTemp.equalsIgnoreCase("true")) {
			// flagResult = true;
			// }

		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return flagResult;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.main_menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.menu_exit:
	        //newGame();
	    	finish();
	    	Log.e("Menu Click", "Exit Menu Clicked");
	        return true;
	    case R.id.menu_preferences:
	    	//showpref();
	    	super.loadUrl("javascript:showpref();");
	    	Log.e("Menu Click", "Preferences Menu Clicked");
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	

	/* Request updates at startup */
	@Override
	protected void onResume() {
		super.onResume();
		locationManager.requestLocationUpdates(provider, 400, 1, this);
	}

	/* Remove the locationlistener updates when Activity is paused */
	@Override
	protected void onPause() {
		super.onPause();
		locationManager.removeUpdates(this);
	}

	@Override
	public void onLocationChanged(Location location) {
		//int lat = (int) (location.getLatitude());
		//int lng = (int) (location.getLongitude());
		
		myLatitude = location.getLatitude();
		myLongitude = location.getLongitude();
		
		
		//latituteField.setText(String.valueOf(lat));
		//longitudeField.setText(String.valueOf(lng));
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		Toast.makeText(this, "Enabled new provider " + provider,
				Toast.LENGTH_SHORT).show();

	}

	@Override
	public void onProviderDisabled(String provider) {
		Toast.makeText(this, "Disenabled provider " + provider,
				Toast.LENGTH_SHORT).show();
	}
	
	


}